package com.itheima.health.service.impl;

import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.dto.OrderSettingDTO;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;

    /**
     * 根据日期设置人数
     * @param orderSetting
     */
    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        OrderSetting orderSetting1 = orderSettingDao.selectByDate(orderSetting);
        if (orderSetting1 != null)
            orderSettingDao.editNumberByDate(orderSetting);
        else
            orderSettingDao.addNumberByDate(orderSetting);
    }

    /**
     * 查看预约情况
     * @param year
     * @param month
     */
    @Override
    public  List<OrderSettingDTO> getOrderSettingByMonth(String year, String month){
        String dateStr = year + "0" + month; // 指定年月
        LocalDate date = LocalDate.parse(dateStr + "01", DateTimeFormatter.BASIC_ISO_DATE);
        LocalDate beginDay = date.with(TemporalAdjusters.firstDayOfMonth()); // 指定年月的第一天
        LocalDate endDay = date.with(TemporalAdjusters.lastDayOfMonth()); // 指定年月的最后一天

        List<LocalDate> dateList = new ArrayList<>();
        List<OrderSettingDTO> orderSettings = new ArrayList<>();
        dateList.add(beginDay);

        while (!beginDay.equals(endDay)){
            beginDay = beginDay.plusDays(1);//日期计算，获得指定日期后1天的日期
            dateList.add(beginDay);
        }
        for (LocalDate localDate : dateList) {
            OrderSetting orderSetting = orderSettingDao.getOrderSettingByMonth(localDate);
            if (orderSetting == null){
                orderSetting = OrderSetting.builder()
                        .orderDate(null)
                        .number(0)
                        .reservations(0)
                        .build();
            }
            if (orderSetting.getNumber() == 0){
                continue;
            }
            OrderSettingDTO orderSettingDTO = OrderSettingDTO.builder()
                    .date(localDate.getDayOfMonth())
                    .number(orderSetting.getNumber())
                    .reservations(orderSetting.getReservations())
                    .build();
            orderSettings.add(orderSettingDTO);
        }
        return orderSettings;

    }
}
